package org.rslai.tcedit.web.admin;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.validator.InvalidStateException;
import org.hibernate.validator.InvalidValue;
import org.rslai.tcedit.domain.Role;
import org.rslai.tcedit.domain.User;
import org.rslai.tcedit.domain.UserDetails;
import org.rslai.tcedit.exception.ApplicationException;
import org.rslai.tcedit.util.HttpUtil;
import org.rslai.tcedit.web.core.AbstractMvcController;

/**
 * 用户管理
 * 
 * @author rslai
 * 
 * @spring.bean name="/admin/user.jspx"
 */
public class UserController extends AbstractMvcController {

	@Override
	public Map<String, Object> getModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String method = request.getMethod();
		Map<String, Object> map = new HashMap<String, Object>();
		User user = null;

		String action = HttpUtil.getString(request, "action", "").toLowerCase();
		String userID = HttpUtil.getString(request, "id", "").toLowerCase();

		try {
			map.put("roles", roleService.queryBonding(false)); // 添加系统角色信息

			if (action.equals("delete")) { // 删除
				user = (User) userService.query(User.class, userID);
				userService.delete(user);
				response.sendRedirect("/admin/userList.jspx");
				user = null;
			}else if (method.equals("GET")) {
				if  (userID.isEmpty()) { // 新增（返回空对象） 
					user = new User();
				} else { // 查询
					user = (User) userService.query(User.class, userID);
				}
			}else if(method.equals("POST")) {
				if (action.equals("create")) { // 新增
					user = (User) HttpUtil.createFormBean(request, User.class);
					user.setCreatedDate(new Date());
					userService.create(user, new UserDetails(), getUserRoles(request));
					response.sendRedirect("/admin/userList.jspx");
				} else if (action.equals("update")) { // 修改
					User formUser = (User) HttpUtil.createFormBean(request, User.class);
					user = (User) userService.query(User.class, userID);
					user.setUsername(formUser.getUsername());
					user.setRealName(formUser.getRealName());
					user.setEmail(formUser.getEmail());
					user.setLocked(formUser.getLocked());
					userService.update(user, user.getUserDetails(), getUserRoles(request));
					response.sendRedirect("/admin/userList.jspx");
				}
			}
		} catch(Exception e) {
			map.put("error", convertException(e));
		}

		map.put("action", action);
		map.put("user", user);

		return map;
	}

	@Override
	public String getView(HttpServletRequest request, HttpServletResponse response) {
		return "/admin/user.htm";
	}

	private String convertException(Exception e) throws Exception {
		if (e instanceof ApplicationException) {
			return e.getMessage();
		} else if (e instanceof InvalidStateException) {
			StringBuffer sb = new StringBuffer(128);
			InvalidValue[] ivs = ((InvalidStateException) e).getInvalidValues();
			for (InvalidValue iv : ivs)
				sb.append(iv.getMessage()).append("<br/>");
			return sb.toString();
		}
		throw e;
	}

	/**
	 * 返回用户拥有的系统权限
	 * @param request
	 * @return
	 */
	private Set<Role> getUserRoles (HttpServletRequest request) {
		Set<Role> roles = new HashSet<Role>(0);;
		for(String roleID : HttpUtil.getStringValues(request, "roleID")) {
			roles.add((Role) roleService.query(Role.class, roleID));
		}
		return roles;
	}

}